package org.batatasframework.values;

import java.util.HashMap;
import java.util.Map;

import org.springframework.util.Assert;

import cn.bonoon.kernel.util.StringHelper;

/**
 * 格式如：nnn0:vv0,nnn1:vv1,nnn2:vv2的格式
 * @author jackson
 *
 */
public class MappedValueReader extends AbstractValueReader{
	
	private final Map<String, Object> values;
	
	public MappedValueReader(Map<String, Object> values){
		this.values = values;
	}

	public MappedValueReader(){
		this.values = new HashMap<>();
	}
	
	public static MappedValueReader valueOf(String value){
		return valueOf(value, ",", ":");
	}
	
	public static MappedValueReader valueOf(String value, String itemSeparate, String valueSeparate){
		MappedValueReader mValue = new MappedValueReader();
		if(null != value){
			String[] items = value.split(itemSeparate);
			int vsLen = valueSeparate.length();
			for(String item : items){
				if(StringHelper.isEmpty(item)) continue;
				
				int p = item.indexOf(valueSeparate);
				if(p > 0){
					mValue.put(item.substring(0, p), item.substring(p + vsLen));
				}else{
					mValue.put(item, null);
				}
			}
		}
		return mValue;
	}
	
	public void put(String name, Object value){
		Assert.notNull(values.put(name, value), "存在重复的定义：" + value);
	}

	@Override
	public ValueGetter getValue(String name) {
		return ObjectValueGetter.valueOf(values.get(name));
	}
}
